package org.algorithm.二师兄.链表;

import org.algorithm.common.ListNode;

/**
 * good luck guys
 * keep learing for algorithm
 * @Link {https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof/}
 */
public class 反转链表 {


    public static void main(String[] args) {
//        ListNode node = new ListNode(6);
//        ListNode node1 = new ListNode(5);
//        ListNode node2 = new ListNode(4);
//        ListNode node3 = new ListNode(3);
//        ListNode node4 = new ListNode(2);
//        ListNode node5 = new ListNode(1);
//
//        node.next = node1;
//        node1.next = node2;
//        node2.next = node3;
//        node3.next = node4;
//        node4.next = node5;

        ListNode node = ListNode.build(6,5,4,3,2,1);
        ListNode.print(node);

        System.out.println();

        ListNode reverseNode = reverseListNode(node);

        ListNode.print(reverseNode);
    }

    //  6 -> 5 -> 4 -> 3
    //  6 -> 5 -> 4 <- 3
    //  p    c    n
    private static ListNode reverseListNode(ListNode node) {
        if (node == null || node.next == null) return node;
        //
//        ListNode prev = node;
//        ListNode curr = node.next;
//        prev.next = null;
//
//        while (curr != null) {
//            ListNode next = curr.next;
//            curr.next = prev;
//            prev = curr;
//            curr = next;
//        }


        ListNode head = node, prev = null;
        while (head != null) {
            ListNode temp = head.next;
            head.next = prev;
            prev = head;
            head = temp;
        }

        return prev;
    }


}
